package com.hilaver.dzmis.exhibition.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Blob;
import java.util.Date;
import java.util.Set;

import com.hilaver.dzmis.exhibition.servlet.AbstractBaseServlet;
import com.hilaver.dzmis.exhibition.utils.Constants;

public class SimpleObj2XML {
	
	private static String GET = "get";
	
	public static String toXMLFragment(Object obj) throws Exception{
		
		Field[] fields;
		if(obj.getClass().getName().indexOf("$") != -1){ //The class is a hibernate delegating class
			fields = obj.getClass().getSuperclass().getDeclaredFields();
		}else{
			fields = obj.getClass().getDeclaredFields();
		}
		StringBuffer sb = new StringBuffer();
		
		for(Field field: fields){
			String methodName = GET + firstLetterToUpcase(field.getName());
			Method method = obj.getClass().getMethod(methodName, new Class[]{});
			Object value = method.invoke(obj, new Object[]{});
			sb.append("<" + field.getName() + ">");
			if(isSimpleType(method.getReturnType())){
				sb.append(Constants.XML_CDATA[0]);
				sb.append(value==null?"":value);
				sb.append(Constants.XML_CDATA[1]);
			}else if(isBlob(method.getReturnType())){
				String photoName = (String)obj.getClass().getMethod(methodName + "Name", new Class[]{}).invoke(obj, new Object[]{});
				writeFile(AbstractBaseServlet.UPLOAD_TEMP_REAL_DIR + photoName, (Blob)value);
			}
			
			sb.append("</" + field.getName() + ">");
		}
		
		return sb.toString();
	}
	
	private static String firstLetterToUpcase(String in){
		return in.substring(0, 1).toUpperCase() + in.substring(1);
	}
	
	public static Boolean isSimpleType(Class clazz){
		if(clazz.equals(Integer.class)){
			return true;
		}
		if(clazz.equals(Float.class)){
			return true;
		}
		if(clazz.equals(Double.class)){
			return true;
		}
		if(clazz.equals(String.class)){
			return true;
		}
		if(clazz.equals(Date.class)){
			return true;
		}
		return false;
	}
	
	public static Boolean isBlob(Class clazz){
		if(clazz.equals(Blob.class)){
			return true;
		}
		return false;
	}
	
	public static void writeFile(String filePath, Blob fileBlob){
		if(fileBlob == null){
			return;
		}
		File file = new File(filePath);
		if(file.exists()){
			return;
		}
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			is = fileBlob.getBinaryStream();
			fos = new FileOutputStream(filePath);
			byte[] buf = new byte[102400];
			   
			int len;
			while((len = is.read(buf))!= -1){
			    fos.write(buf,0,len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(fos != null){
					fos.close();
				}
				if(is != null){
					is.close();
				}
			} catch (IOException e) {
			}
		}
	}
}
